import type { CategoryItem, TreeNode } from '@/indexDB/initCategory'

export const buildCategoryTree = (list: CategoryItem[]) => {
  const level1List = list.filter(each => each.level === 1)
  const level2List = list.filter(each => each.level === 2)
  const level3List = list.filter(each => each.level === 3)

  const tree: TreeNode[] = level1List.map(node1 => {
    const { id } = node1
    const children1: TreeNode[] = []
    level2List.forEach(node2 => {
      if (node2.parentId === id) {
        children1.push({
          ...node2,
          children: level3List.filter(node3 => node3.parentId === node2.id)
        })
      }
    })
    return {
      ...node1,
      children: children1
    }
  })

  return tree
}